package com.yjf.ljr.activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;

import com.yjf.ljr.R;
import com.yjf.ljr.adapter.CommonAdapter;
import com.yjf.ljr.adapter.CommonAdapter.HandleCallBack;
import com.yjf.ljr.common.CommonData;
import com.yjf.ljr.dataclass.InvestProjectDataClass;
import com.yjf.ljr.dataclass.InvestProjectDataClass.InvestProjectInfo;
import com.yjf.ljr.parser.RequestBuilder.RequestObject;
import com.yjf.ljr.util.AppUtil;
import com.yjf.ljr.view.XListView;
import com.yjf.ljr.view.XListView.IXListViewListener;

/**
 * 投资的项目
 * 
 * @author dongxie
 */
public class InvestProjectActivity extends IjActivity {

	@ID("xlvInvestProject")
	private XListView mXlvInvestProject;

	private CommonAdapter mCommonAdapter;
	private List<InvestProjectInfo> mData = new ArrayList<InvestProjectInfo>();
	private final int mPageSize = 10;
	private int mCurPage = 1;
	private boolean mIsGettingData = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_invest_project);

		initControls();

		showProgressDialog();
		new InvestProjectTask(mPageSize, mCurPage, false).execute();
	}

	/** 初始化控件 **/
	private void initControls() {
		setLeftBtnClick();
		setTitleStr("投资的项目");
		mCommonAdapter = new CommonAdapter(this, mData, R.layout.item_invest_project, ViewHolder.class, mHandleCallBack);
		mXlvInvestProject.setAdapter(mCommonAdapter);
		mXlvInvestProject.setPullLoadEnable(true);
		mXlvInvestProject.setPullRefreshEnable(true);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		mXlvInvestProject.setRefreshTime(sdf.format(new Date()));
		mXlvInvestProject.mFooterView.hide(); // 隐藏更多
		mXlvInvestProject.setXListViewListener(new MyXListViewListener());
	}

	private class MyXListViewListener implements IXListViewListener {
		@Override
		public void onRefresh() {
			if (!mIsGettingData) {
				mCurPage = 1;
				new InvestProjectTask(mPageSize, mCurPage, false).execute();
			}
		}

		@Override
		public void onLoadMore() {
			if (!mIsGettingData) {
				new InvestProjectTask(mPageSize, ++mCurPage, true).execute();
			}
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case CommonData.REQUEST_CODE_LOGIN:
				showProgressDialog();
				mCurPage = 1;
				mData.clear();
				mCommonAdapter.notifyDataSetChanged();
				new InvestProjectTask(mPageSize, mCurPage, false).execute();
				break;
			}
		}
		super.onActivityResult(requestCode, resultCode, intent);
	}

	class InvestProjectTask extends AsyncTask<Void, Void, String> {

		private int pageSize;
		private int curPage;
		private boolean isAdd = false;
		private InvestProjectDataClass dc = new InvestProjectDataClass();

		public InvestProjectTask(int pageSize, int curPage, boolean isAdd) {
			super();
			this.pageSize = pageSize;
			this.curPage = curPage;
			this.isAdd = isAdd;
		}

		@Override
		protected void onPreExecute() {
			mIsGettingData = true;
		}

		@Override
		protected String doInBackground(Void... params) {
			RequestObject requestobj = new RequestObject();
			requestobj.method = "appInvestProject";
			requestobj.map.put("pageSize", pageSize);
			requestobj.map.put("pageNumber", curPage);
			return requestDataAndGetErrorMsg(requestobj, dc);
		}

		@Override
		protected void onPostExecute(String result) {
			if ("-1".equals(dc.code)) {
				loginWebview();
				return;
			}
			if (!TextUtils.isEmpty(result)) {
				showToast(result);
				mCommonAdapter.notifyDataSetChanged();
				mXlvInvestProject.mFooterView.hide();
			} else {
				if (dc.list == null) {
					dismissProgressDialog();
					showToast(dc.msg);
					mXlvInvestProject.stopRefresh();
					mXlvInvestProject.stopLoadMore();
					mIsGettingData = false;
					return;
				}
				if (!isAdd) {
					mData.clear();
				}

				if (dc.list != null && dc.list.size() > 0) {
					mData.addAll(dc.list);

					if (mData.size() <= (dc.totalPage - 1) * pageSize) {
						mXlvInvestProject.mFooterView.show();
					} else {
						mXlvInvestProject.mFooterView.hide();
					}
				}
				mCommonAdapter.notifyDataSetChanged();
			}
			mXlvInvestProject.stopRefresh();
			mXlvInvestProject.stopLoadMore();
			dismissProgressDialog();
			mIsGettingData = false;
		}
	}

	public static class ViewHolder {
		TextView tvProjectName;
		TextView tvProjectMoney;
		TextView tvProjectTime;
		TextView tvProjectStatus;
		TextView tvProjectRate;
		TextView tvProjectIncome;
	}

	private HandleCallBack mHandleCallBack = new HandleCallBack() {

		@Override
		public void handle(int position, View convertView, ViewGroup parent, Object holder, Object item) {
			final InvestProjectInfo info = (InvestProjectInfo) item;
			ViewHolder h = (ViewHolder) holder;
			String tempStatuStr = "";
			String tempTime = "";
			AppUtil.setViewText(h.tvProjectName, info.loanName);
			AppUtil.setViewHtml(h.tvProjectMoney, info.benefitAmount + "<font color='#666666'>元</font>");

			if ("1".equals(info.status)) {
				tempStatuStr = "正在投资";
				tempTime = "投资时间：";
			} else if ("2".equals(info.status)) {
				tempStatuStr = "投资完成";
				tempTime = "投资时间：";
			} else if ("3".equals(info.status)) {
				tempStatuStr = "未到投资时间";
				tempTime = "投资时间：";
			} else if ("4".equals(info.status)) {
				tempStatuStr = "还款完成";
				tempTime = "完成时间：";
			} else if ("5".equals(info.status) || "7".equals(info.status)) {
				tempStatuStr = "正在还款 ";
				tempTime = "还款时间：";
			} else if ("6".equals(info.status)) {
				tempStatuStr = "已过投资时间";
				tempTime = "投资时间：";
			} else if ("8".equals(info.status)) {
				tempStatuStr = "交易失败";
				tempTime = "投资时间：";
			} else if ("9".equals(info.status)) {
				tempStatuStr = "提前还款";
				tempTime = "还款时间：";
			}
			if (!TextUtils.isEmpty(info.date) && info.date.length() > 10) {
				AppUtil.setViewText(h.tvProjectTime, tempTime + info.date.substring(0, 10));
			} else {
				AppUtil.setViewText(h.tvProjectTime, tempTime + info.date);
			}
			AppUtil.setViewText(h.tvProjectStatus, "状态：" + tempStatuStr);
			String income = TextUtils.isEmpty(info.benifit) ? "0" : info.benifit;
			AppUtil.setViewHtml(h.tvProjectIncome, income);
			String rate = info.interestRate;
			if (rate.endsWith("%")) {
				rate = rate.substring(0, rate.length() - 1);
			}
			AppUtil.setViewText(h.tvProjectRate, "利率：" + rate + "%");
			if (!TextUtils.isEmpty("demandid")) {
				convertView.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						Intent intent = new Intent(InvestProjectActivity.this, ProjectDetailActivity.class);
						intent.putExtra("demandId", info.demandId);
						startActivity(intent);
					}
				});
			}

		}
	};
}
